package com.homeinns.lyx.server.service;


import com.homeinns.client.feignclient.ProductClient;
import com.homeinns.common.DecreaseStockInput;
import com.homeinns.common.ProductInfoOutput;
import com.homeinns.lyx.server.dataobject.OrderDetail;
import com.homeinns.lyx.server.dataobject.OrderMaster;
import com.homeinns.lyx.server.dto.OrderDTO;
import com.homeinns.lyx.server.enums.OrderStatus;
import com.homeinns.lyx.server.enums.PayStatusEnum;
import com.homeinns.lyx.server.repository.OrderDetailRepository;
import com.homeinns.lyx.server.repository.OrderMasterRepository;
import com.homeinns.lyx.server.utils.KeyUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private ProductClient productClient;

    @Autowired
    private OrderMasterRepository orderMasterRepository;

    @Autowired
    private OrderDetailRepository orderDetailRepository;

    @Override
    public OrderDTO create(OrderDTO orderDTO) {

        String orderId = KeyUtil.genUniqueKey();
        List<String> productIdList = orderDTO.getOrderDetails()
                .stream().map(OrderDetail::getProductId).collect(Collectors.toList());
        List<ProductInfoOutput> productInfoOutputs=productClient.listForOrder(productIdList);
        BigDecimal orderAmount = new BigDecimal(BigInteger.ZERO);
        for(OrderDetail orderDetail:orderDTO.getOrderDetails()){
            for(ProductInfoOutput productInfoOutput:productInfoOutputs){
                if(productInfoOutput.getProductId().equals(orderDetail.getProductId())){
                    orderAmount = productInfoOutput.getProductPrice().multiply(new BigDecimal(orderDetail.getProductQuantity()));
                    BeanUtils.copyProperties(productInfoOutput, orderDetail);
                    orderDetail.setOrderId(orderId);
                    orderDetail.setDetailId(KeyUtil.genUniqueKey());
                    orderDetailRepository.save(orderDetail);
                }

            }
        }
        /*扣库存*/
        List<DecreaseStockInput> decreaseStockInputs=orderDTO.getOrderDetails().stream()
                .map(e->new DecreaseStockInput(e.getProductId(),e.getProductQuantity())).collect(Collectors.toList());
        productClient.decreaseStock(decreaseStockInputs);
        OrderMaster orderMaster = new OrderMaster();
        orderMaster.setOrderId(orderId);
        orderMaster.setOrderAmount(orderAmount);
        orderMaster.setOrderStatus(OrderStatus.NEW.getCode());
        orderMaster.setPayStatus(PayStatusEnum.WAIT.getCode());
        orderMasterRepository.save(orderMaster);
        return orderDTO;
    }
}
